package com.xjscrm.console.chat.mq.impl;

import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.MicaTalkFriendResultMsg;
import com.uzai.mobile.collect.api.enums.MicaMsgType;
import com.xjscrm.console.chat.enums.ChatTalkRecordSendStatus;
import com.xjscrm.console.chat.mq.MsgHandler;
import com.xjscrm.console.dto.chat.ChatTalkRecordQueryDTO;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/11 18:14
 */
@Component
@Slf4j
public class TalkResulMsgHandler implements MsgHandler<MicaTalkFriendResultMsg> {

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;

    @Autowired
    private ChatTalkRecordService chatTalkRecordService;

    @Override
    public MicaMsgType msgType() {
        return MicaMsgType.TALK_FRIEND_RESULT;
    }

    @Override
    public Class<MicaTalkFriendResultMsg> msgClass() {
        return MicaTalkFriendResultMsg.class;
    }

    @Override
    public void doHandle(MicaTalkFriendResultMsg micaTalkFriendResultMsg) {
        MicaTransDto micaTransDto = baseCache.get();

        Long taskId = micaTalkFriendResultMsg.getTaskId();

        ChatTalkRecordQueryDTO query = new ChatTalkRecordQueryDTO();
        query.setMerId(micaTransDto.getMerId());
        query.setId(taskId);

        ChatTalkRecord byId = chatTalkRecordService.getById(query);
        if (Objects.isNull(byId)) {
            log.error("聊天消息记录未找到: {}", taskId);
            return;
        }

        byId.setWxSendTime(micaTalkFriendResultMsg.getCreateTime().intValue());
        byId.setMsgId(Long.valueOf(micaTalkFriendResultMsg.getMsgId()));
        byId.setRemoteMsgId(Long.valueOf(micaTalkFriendResultMsg.getMsgRemoteId()));
        byId.setSendStatus(ChatTalkRecordSendStatus.send_success.getCode());

        chatTalkRecordService.updateById(byId);
    }
}
